import { Context, Next } from 'koa';
import { PrismaClient } from '@prisma/client';
import { createUserSchema, updateUserSchema } from '../validation/userValidation';

const prisma = new PrismaClient();

// 获取所有用户
export const getUsers = async (ctx: Context, _next: Next) => {

    try {
        const users = await prisma.user.findMany();
        ctx.body = users;
    } catch (error) {
        ctx.status = 500;
        ctx.body = { error: '获取用户列表失败' };
    }
};

// 根据 ID 获取用户
export const getUserById = async (ctx: Context) => {
    const id = ctx.params.id;
    try {
        const user = await prisma.user.findUnique({
            where: { id: id },
            include: { school: true }
        });
        if (user) {
            ctx.body = user;
        } else {
            ctx.status = 404;
            ctx.body = { error: '用户不存在' };
        }
    } catch (error) {
        ctx.status = 500;
        ctx.body = { error: '获取用户信息失败' };
    }
};

// 创建新用户
export const createUser = async (ctx: Context) => {
    const { name, email, schoolId } = ctx.request.body as { name: string; email: string; schoolId?: string };

    // 参数验证
    const { error } = createUserSchema.validate({ name, email, schoolId });
    if (error) {
        ctx.status = 400;
        ctx.body = { error: error.details[0].message };
        return;
    }

    try {
        const user = await prisma.user.create({
            data: { name, email, schoolId: schoolId ? schoolId : null }
        });
        ctx.status = 201;
        ctx.body = user;
    } catch (error) {
        ctx.status = 500;
        ctx.body = { error: '创建用户失败' + error };
    }
};

// 更新用户信息
export const updateUser = async (ctx: Context) => {
    const id = ctx.params.id;
    const { name, email, schoolId } = ctx.request.body as { name?: string; email?: string; schoolId?: string };

    // 参数验证
    const { error } = updateUserSchema.validate({ name, email, schoolId });
    if (error) {
        ctx.status = 400;
        ctx.body = { error: error.details[0].message };
        return;
    }

    try {
        const user = await prisma.user.update({
            where: { id: id },
            data: { name, email, schoolId: schoolId ? schoolId : null }
        });
        ctx.body = user;
    } catch (error) {
        ctx.status = 500;
        ctx.body = { error: '更新用户信息失败' };
    }
};

// 删除用户
export const deleteUser = async (ctx: Context) => {
    const id = ctx.params.id;
    try {
        const user = await prisma.user.delete({
            where: { id: id }
        });
        ctx.body = user;
    } catch (error) {
        ctx.status = 500;
        ctx.body = { error: '删除用户失败' };
    }
};